<?php
namespace Admin\Controller;
use Think\Controller;
use Common\Controller\BaseController;

/**
 * 服务人员新单、续费查账管理
 *
 * @author    	ZhangYe <banfg56@gmail.com>
 * @date      	08/31/2016
 * @Controller  Pays
 */
class PaysController extends BaseController {

	const S_TIME = 'start_time';
	const E_TIME = 'end_time';
	const D_TIME = 'd_time';

	public function index(){
		$psize = I('get.psize', $this->m_psize,'intval');
		if( !$psize )
			$psize = $this->m_psize;
		else if( $psize > 20 )
			$psize = $this->m_psize;
		$audit = I('get.audit','-1','intval');
		$name = I('get.name','','trim');
		$phone = I('get.phone','','trim');
		$stime = I('get.Stime','','trim');
		$etime = I('get.Etime','','trim');
		$MPay = D("pay_record");
		$wheres = array();
		$wheres['_string'] = '1=1';
		$wheres['pay_record.creator'] = array('eq', $this->m_user['user_id']);
		if($audit >= 0 )
			$wheres['pay_record.audit_res'] = array('eq', $audit );
		if( $name )
			$wheres['pay_record.pay_name'] = array('like', "%".$name."%");
		if( $phone ){
			$wherec = array();
			if( preg_match('#^\d+$#is', $phone ) ){
				$wherec['_logic'] = 'OR';
				if( strlen( $phone) == 11 )
					$wherec['pay_record.customer_phone'] = array('eq', $phone);
				$wherec['pay_record.customer_qq'] = array('eq', $phone);
				$wherec['pay_record.customer_weixin_id'] = array('eq',$phone );
				$wheres['_complex'] = $wherec;
			}
			else{
				$wheres['pay_record.customer_weixin_id'] = array('eq', $phone);
			}

		}
		if( $stime && $etime ){
			$tm_s = strtotime( $stime );
			$tm_e = strtotime( $etime );
			if( $tm_e < $tm_s ){
				break;
			}
			else{
				$stime = date('Y-m-d 00:00:00', $tm_s );
				$etime =  date('Y-m-d 23:59:59', $tm_e );
				$wheres['pay_record.pay_time'] = array('between', array($stime, $etime ));
			}
		}
		elseif( $stime && !$etime ){
			$tm_s = strtotime( $stime );
			$stime = date('Y-m-d 00:00:00', $tm_s );
			$wheres['pay_record.pay_time']  = array('gt', $stime );
		}
		else if( $etime && !$stime ){
			$tm_e = strtotime( $etime );
			$etime = date('Y-m-d 23:59:59', $tm_e );
			$wheres['pay_record.pay_time']  = array('lt', $etime );
		}

		$cnt = $MPay->where( $wheres )->count();
		$Page = new \Common\ORG\Page( $cnt, $psize );

		$res = array('rcode'=>1,'data'=>NULL, 'msg'=> 'OK');
		// 修改jzd
		$dlist = $MPay->where( $wheres )
					  ->order("pay_record.create_time desc ")
					  ->limit($Page->firstRow.','.$Page->listRows )
					  ->select();
		if( $dlist ){
			$res['rcode'] = 1;
			$res['data'] = $dlist;
			$res['pall'] =  $Page->getTotalPages();
			$res['p'] = $Page->nowPage;
			$res['psize'] = $psize;

		}else{
			$res['msg'] = "查账内容为空";
		}

		e_json( $res );
	}

	/*查账信息是否重复判断*/
	public function onePay(){
		//
	}


	public function  products(){
		$res = array('rcode'=>0,'data'=>NULL, 'msg'=> 'OK');
		if( IS_GET ){//js穿过来的两个方法写在一起了
			$Mu = D("User");
			$res['data'] = array();
			$res['data']['product'] = M('Product')->field("product_id,name")->select();
			// jzd 修改
			foreach ($res['data']['product'] as &$price_value) {
	    		$p_price['product_id'] = $price_value['product_id'];
	    		$price_value['price_list'] = M('product_price')->field("price_id, name as price_name")->where($p_price)->select();
			}

			// $res['data']['product'] = A('contract')->Contract_Upgrade();
			$res['data']['price']  =   M('ProductPrice')->field("price_id,product_id,name")->select();
			$res['data']['xufei'] = $Mu->subsector_user( $this->m_user['sector_id']);
			$wheres = array();
			// 查找只能是本人的客户,否则不能查找出来
			$wheres['customer_xufei.user_id'] = array('eq', $this->m_user['user_id']);
			$wheres['customer_xufei.end_time'] = array('exp','is null');
			$res['data']['customer'] = M('CustomerXufei')->distinct(true)->field("customer_xufei.user_id,customer.customer_id,customer.nickname,customer.customer_id,customer.phone,customer.weixin_id")
														 ->join("LEFT JOIN customer on customer.customer_id=customer_xufei.customer_id")
														 ->where($wheres)
														 ->select();
			$res['rcode'] = 1;
			$res['sql'] = M('CustomerXufei')->getLastSql();
		}
		else{
			/*获取最新一份合同信息*/
			$Mcon = M("Contract");
			$wheres = $arr = array();
			$customer = I('post.customer','-1','intval');
			$wheres['contract.customer_id'] = array('eq', $customer);


			$order = "locate(contract.state,'0,1,3,2,-1') asc";
			$dataCon = $Mcon
			                ->field("c.nickname as customer_name,u.nickname as service_name,p.name as product_name,contract.*")
							->join("LEFT JOIN customer c on c.customer_id=contract.customer_id")
							->join("LEFT JOIN user u on u.user_id=c.sales_person")
							->join("LEFT JOIN product p on p.product_id=contract.product_id")
							->where( $wheres )
							->order( $order )
							->find();
			// jzd 修改查询合同期限
			if (!empty($dataCon)) {
				foreach ($dataCon as $k => $v) {
					if ($k == self::S_TIME) $arr[self::S_TIME] = strtotime($v);
					if ($k == self::E_TIME) $arr[self::E_TIME] = strtotime($v);
				}
				$J_Time = D('Pays')->judge_time($arr);
				if ($J_Time['r']) {
					switch ($J_Time['r']) {
						case '1'://合同小于三个月
							$dataCon[self::D_TIME]=1;
							break;
						case '2'://合同大于三个月
							$dataCon[self::D_TIME] = 2;
							break;
					}
				}else{
					$dataCon[self::D_TIME] = 3;
				}
				if( $dataCon ){
					$res['rcode'] = 1;
					$res['data'] = $dataCon;
					$res['msg'] = 'OK';
				}else{
					$res['msg'] = '获取客户合同信息失败'.$Mcon->getLastSql();
				}
			}else{

			}

		}
		e_json( $res );
	}
	/**
	 * 是否撞单判断
	 *
	 * 首先检测查账中是否提交客户资料
	 * 如果不存在，则在用户表中检测
	 *
	 */
	public function oneUser(){
		$MPay = M('pay_recor');
		$MCustomer = M("customer");
		$res = array('rcode'=>0,'data'=>NULL, 'msg'=> 'OK');
		$wheres = $whereu = array();
		$field = I('post.field','');
		$data = I('post.data',NULL);
		if( $data ){
			if( 'customer_name' == $field){
				$wheres['customer_name'] = array('eq', $data );
				$whereu['login_name'] = array('eq', $data );
			}
			else if( 'customer_phone' === $field ){
				$wheres['customer_phone'] = array('eq', $data );
				$whereu['phone'] = array('eq', $data );
			}
			elseif( 'customer_qq' === $field ){
				$wheres['customer_qq'] = array('eq', $data );
				$whereu['qq'] = array('eq', $data );
			}
			elseif( 'customer_weixin_id' === $field ){
				$wheres['customer_weixin_id'] = array('eq', $data );
				$whereu['weixin_id'] = array('eq', $data );
			}
			elseif( 'customer_name' === $field ){
				$wheres['customer_name'] = array('eq', $data );
				$whereu['login_name'] = array('eq', $data );
			}
			$dfind = $MPay->where( $wheres )->find();
			if( !$dfind ){
				$dfind = $MCustomer->where( $whereu )->find();
				if( $dfind ){
					$res['data'] = $dfind;
					$res['msg'] = "已经存在正式注册用户";
				}else{
					$res['rcode'] = 1;
					$res['msg'] = "OK";
				}
			}else{
				$res['data'] = $dfind;
				$res['msg'] = "新单查账中已经存该用户";
			}
		}
		else{
			$res['msg'] = "提交参数错误";
		}
		$whereu = array();
		e_json( $res );
	}


	// 编辑新单中判断是否撞单
	public function oneUser_edit(){
		$MPay = M('pay_recor');
		$MCustomer = M("customer");
		$res = array('rcode'=>0,'data'=>NULL, 'msg'=> 'OK');
		$wheres = $whereu = array();
		$field = I('post.field','');
		$data = I('post.data',NULL);
		$payrecord_id = I('post.id',NULL);
		// $customer_name_con = I('post.name','');
		if( $data ){
			$resMPy = $MPay->where(array('payrecord_id'=>$payrecord_id))->find();
			if( 'customer_name_edit' == $field){
				if ($data!= $resMPy['customer_name']) {
					$wheres['customer_name'] = array('eq', $data );
					$whereu['login_name'] = array('eq', $data );
				}
			}
			else if( 'customer_phone_edit' === $field ){
				if ($data!=$resMPy['customer_phone']) {
					$wheres['customer_phone'] = array('eq', $data );
					$whereu['phone'] = array('eq', $data );
				}
			}
			elseif( 'customer_qq_edit' === $field ){
				if ($data!=$resMPy['customer_qq']) {
					$wheres['customer_qq'] = array('eq', $data );
					$whereu['qq'] = array('eq', $data );
				}
			}
			elseif( 'customer_weixin_id_edit' === $field ){
				if ($data!=$resMPy['customer_weixin_id']) {
					$wheres['customer_weixin_id'] = array('eq', $data );
					$whereu['weixin_id'] = array('eq', $data );
				}
			}
			if(!$wheres){
					$res['rcode'] = 1;
					$res['msg'] = "OK";
					e_json($res);
			}
			$dfind = $MPay->where( $wheres )->find();
			if( !$dfind ){
				$dfind = $MCustomer->where( $whereu )->find();
				if( $dfind ){
					$res['data'] = $dfind;
					$res['msg'] = "已经存在正式注册用户";
				}else{
					$res['rcode'] = 1;
					$res['msg'] = "OK";
				}
			}else{
				$res['data'] = $dfind;
				$res['msg'] = "新单查账中已经存该用户";
			}
		}
		else{
			$res['msg'] = "提交参数错误";
		}
		e_json( $res );
	}


	/**
	 * 添加新单查账
	 *
	 * @return [type] [description]
	 */
	public function addnew(){
		$res = array('rcode'=>0,'data'=>NULL, 'msg'=> 'OK');
		$Mdo = D("Pays");
		$Mdo->create();
		$payWay = trim($Mdo->pay_way);
		$payTypes = C('PAYS');
		$Mdo->pay_way = isset( $payTypes[$payWay] ) ?  $payTypes[$payWay]  : $payWay;
		$doRes = $Mdo->add_new();
		if( $doRes && $doRes['r'] ){
			$res['rcode'] = 1;
			$res['msg'] = 'OK';
			$res['data'] = $doRes['d'];
		}
		else{
			$res['msg'] = $doRes['i'];
		}

		e_json($res);
	}

	/**
	 * 添加续费查账
	 * @return [type] [description]
	 */
	public function addxufei(){
		$res = array('rcode'=>0,'data'=>NULL, 'msg'=> 'OK');
		$Mdo = D("Pays");
		$Mdo->create();
		/*处理订购产品、报价*/
		$product = I('post.product','0','intval');
		$price = I('post.price','0','intval');
		$Mdo->customer_product = $product;
		$Mdo->customer_price = $price;
		$payWay = trim($Mdo->pay_way);
		$payTypes = C('PAYS');
		$Mdo->pay_way = isset( $payTypes[$payWay] ) ?  $payTypes[$payWay]  : $payWay;
		$doRes = $Mdo->add_xufei();
		if( $doRes && $doRes['r'] ){
			$res['rcode'] = 1;
			$res['msg'] = 'OK';
			$res['data'] = $doRes['d'];
		}
		else{
			$res['msg'] = $doRes['i'];
		}

		e_json( $res );
	}

	public function edit(){
		$res = array('rcode'=>0,'data'=>NULL, 'msg'=> 'OK');
		$MLog = D('Log');
		$log_id = I('post.log_id',false,'intval');
		$title = I('post.title',false,'trim');
		$content = I('post.content',false,'trim');
		$type = I('post.type',false,'intval');
		$addres = $MLog->update_log($log_id, $title, $content, $type);
		if( $addres['r'] ){
			$res['rcode'] = 1;
			$res['msg'] = 'OK';
			$res['data'] = $addres['d'];
		}
		else{
			$res['msg'] = $addres['i'];
		}
		e_json( $res );
	}

	public function paytypes(){
		$res = array('rcode'=>1,'data'=>NULL, 'msg'=> 'OK');
		$_payways = C('PAYS');
		$payways = array();
		$item = array();
		foreach( $_payways as $k=>$v ){
			$item['k'] = $k;
			$item['v'] = $v;
			$payways[] = $item;
			$index++;
		}
		$res['data'] = $payways;
		e_json( $res );
	}

	// 编辑续费查账
	public function editxufei(){
		$res = array('rcode'=>1,'data'=>NULL, 'msg'=> 'OK');
		$Mdo = D("Pays");
		if ($Mdo->create()) {
			 $Mdo->audit_res = 0;
			if ($Mdo->save($this->payrecord_id)) {
				$res['rcode'] = 1;
				$res['msg'] = 'OK';
			}else
			   $res['msg']='编辑失败';
		}
		e_json($res);
	}

	// 编辑新单查账
	public function editnew(){
		$res = array('rcode'=>1,'data'=>NULL, 'msg'=> 'OK');
		$Mdo = D("Pays");
		if ($Mdo->create()) {
			$Mdo->audit_res = 0;
			if ($Mdo->save($this->payrecord_id)) {
				$res['rcode'] = 1;
				$res['msg'] = 'OK';
			}else
			   $res['msg']='编辑失败';
		}
		e_json($res);
	}

	// 得到服务人员姓名
	public function getserver(){
		$customer_sales = I('customer_sales',false,'trim');
		$res = M('user')->field('nickname')->where(array('user_id'=>$customer_sales))->find();
		e_json($res);
	}

	// 获得姓名
	public function getname(){
		$customer_id = I('post.customer',false,'trim');
		$res = M('customer')->field('nickname')->where(array('customer_id'=>$customer_id))->find();
		e_json($res);
	}

	// 添加退款
	public function addfeedback(){
		$res = array('rcode'=>1,'data'=>NULL, 'msg'=> 'OK');
		$fedMes =  I('post.customer_fedbak_edit','','intval');
		$fedMount = I('post.feedbackmount',false,'intval');
		$fedNotes = I('post.feedbacknote','','trim');
		$fedres  = D('Pays')->save_fed(array('customer_id'=>$fedMes,'pay_mount'=>$fedMount,'note'=>$fedNotes));
		e_json($fedres);
	}
	// 退款编辑界面
	public function RetMoney(){
		$res = array('rcode'=>1,'data'=>NULL, 'msg'=> 'OK');
		$Fedit = I('post.customer_fedbak_edit','','intval');
		$Feditmount =  I('post.feedbackmount_edit','','trim');
		$Feditnotes =  I('post.feedbacknote_eidt','','trim');
		$Feditpayrecord = I('post.payrecord_fed_id',false,'intval');
		$Feditres = D('Pays')->edit_fed(array('customer_id'=>$Fedit,'pay_mount'=>$Feditmount,'note'=>$Feditnotes,'payrecord_id'=>$Feditpayrecord));
		if ($Feditres) {
			$res['rcode'] = 1;
			$res['data'] = $Feditres['d'];
		}else{
			$res['msg'] = "编辑失败";
		}
		e_json($res);
		// e_json(array($Fedit,$Feditmount,$Feditnotes,$Feditpayrecord));
	}

	//删除订单界面
	public function del_feedback(){
		$res = array('rcode'=>0,'data'=>NULL, 'msg'=> '');
		$pay_id = I('get.payrecord_id',false,'trim');
		$del_res = D('Pays')->where(array('payrecord_id'=>$pay_id))->delete();
		if ($del_res) {
			$res['rcode'] = 1;
			$res['msg'] = 'OK';
		}else{
			$res['msg'] = '删除信息失败';
		}
		e_json($res);
	}

	//获取续费人员login_name
	public function getlogin_name(){
		$res  = M('customer')->field('login_name')->where(array('customer_id'=>I('customer',false,'intval')))->find();
		e_json($res);
	}

	//获取审核通过人员信息_新单
	public function getCustomerMsg(){
		$dlist = M('pay_record')->field('pay_record.*,product.*,customer.*,product.name as pro_name,product_price.*,user.nickname as unickname,sector.sector_name')
		                       ->join('customer ON customer.customer_id = pay_record.customer_id')
		                       ->join('user ON user.user_id = pay_record.customer_sales')
							   ->join('product ON product.product_id = pay_record.customer_product')
							   ->join('product_price ON product_price.price_id = pay_record.customer_price')
							   ->join('sector ON sector.sector_id = pay_record.customer_sector')
							   ->where(array('pay_record.payrecord_id'=>I('post.payrecord_id',false,'intval')))
							   ->find();

		e_json($dlist);
	}

	//获取审核通过人员信息_续费
	public function getCustomerMsg_xufei(){
		$dlist = M('pay_record')->field('pay_record.*,product.*,customer.*,product.name as pro_name')
		                       ->join('customer ON customer.customer_id = pay_record.customer_id')
							   ->join('product ON product.product_id = payrepay_recordcord.customer_product')
							   ->where(array('pay_record.payrecord_id'=>I('post.payrecord_id',false,'intval')))
							   ->find();

		e_json($dlist);
	}

	// 获取退款信息
	public function feccheck(){
		$dlist = M('pay_record')->field('pay_record.*,customer.*')
		                       ->join('customer ON customer.customer_id = pay_record.customer_id')
							   ->where(array('pay_record.payrecord_id'=>I('post.payrecord_id',false,'intval')))
							   ->find();
		e_json($dlist);
	}

	// 获取退款人的信息
	public function Gtype(){
		$wheres = array();
		$wheres['customer_xufei.user_id'] = array('eq', $this->m_user['user_id']);
		$wheres['customer_xufei.end_time'] = array('exp','is null');
		$wheres['contract.state'] = 1;
		$res['data'] = M('CustomerXufei')->distinct(true)->field("customer_xufei.user_id,customer.customer_id,customer.nickname,customer.customer_id,customer.phone,customer.weixin_id")
													 ->join('contract ON contract.customer_id = customer_xufei.customer_id')
													 ->join("LEFT JOIN customer on customer.customer_id=customer_xufei.customer_id")
													 ->where($wheres)
													 ->select();
		$res['rcode'] = 1;
		$res['sql'] = M('CustomerXufei')->getLastSql();
 		e_json($res);
	}

	// 产品二级联动
	public function twiceCon(){
		$res['list']= D('Pays')->general();
		$res['rcode'] = 1;
		e_json($res);
	}
}